import 'package:example/app/data/model/article_bean.dart';
import 'package:example/app/data/model/page_bean.dart';
import 'package:example/app/data/repository/wan_android_repository.dart';
import 'package:example/index.dart';

class SquarePageLogic extends BaseViewModel {

  /// 文章列表
  List<ArticleBean> articles = <ArticleBean>[];

  RefreshController refreshController = RefreshController(initialRefresh: false);
  int currentPage = 0;

  @override
  void onReady() async{
    super.onReady();
    setBusy();
    onRefresh();
  }

  /// 加载数据
  Future<PageBean<ArticleBean>?>? loadData()async{
    try {
      var result = await WanAndroidRepository.getSquareArticleList(page: currentPage);
      return result;
    }catch(e,s){
      handlerError(e, s);
      return null;
    }
  }

  /// 刷新数据
  onRefresh() async {
    currentPage = 0;
    PageBean<ArticleBean>? model = await loadData();
    if (model == null) {
      refreshController.refreshFailed();
      return;
    } else {
      refreshController.refreshCompleted();
    }
    if (model.over == true) {
      refreshController.loadNoData();
    }else{
      refreshController.loadComplete();
    }

    if (model.datas?.isNotEmpty == true) {
      articles.clear();
      articles.addAll(model.datas!);
      currentPage++;
      setIdle();
    }
  }

  onLoadMore() async {
    PageBean<ArticleBean>? model = await loadData();
    if (model == null) {
      refreshController.loadFailed();
      return;
    }
    if (model.over == true) {
      refreshController.loadNoData();
    } else {
      refreshController.loadComplete();
    }

    if (model.datas?.isNotEmpty == true) {
      articles.addAll(model.datas!);
      currentPage++;
      update();
    }
  }

}
